
import models, constants, aws_pass
import cgi,datetime,logging,sys
import os,hashlib,hmac,base64,time,urllib
import time, httplib
import json
from xml.dom.minidom import parseString
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app


stdin = sys.stdin
stdout = sys.stdout
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdin = stdin
sys.stdout = stdout

logging.basicConfig(level=logging.DEBUG)

class SearchBooks(webapp.RequestHandler):

    def get(self):
        author = self.request.get('author')
        browse_node_id = self.request.get('browse_node_id')
        keyword = self.request.get('keyword')
        page = self.request.get('page')

        params = dict()
        params['Service']        = 'AWSECommerceService',
        params['AWSAccessKeyId'] = aws_pass.AWS_ACCESS_KEY_ID
        params['Version']        = aws_pass.AWS_VERSION
        params['Operation']      = 'ItemSearch'
        params['SearchIndex']    = 'Books'
        params['ItemPage']       = page
        params['Timestamp']      = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime())
        params['ResponseGroup']  = 'ItemAttributes,Images'

        id_str = ""
        if author != "":         id_str = params['Author']     = author
        if browse_node_id != "": id_str = params['BrowseNode'] = browse_node_id
        if keyword != "":        params['Keywords']            = keyword

        aws_url = self.get_aws_url(params)

        h = httplib.HTTPConnection(aws_pass.AWS_URL)
        h.request('GET', aws_url)
        response = h.getresponse()
        result = self.parse(response.read())

        # set location
        if id_str != "":
            query = db.GqlQuery("SELECT * FROM Node WHERE id_str = :id_str", id_str=id_str)
            if query.count() > 0:
                data = query.fetch(1)[0]
                result['ParentX'] = float(data.x)
                result['ParentY'] = float(data.y)

        self.response.out.write(json.JsonWriter().write(result))

    def get_aws_url(self, params):
        keys = params.keys()
        keys.sort()

        pairs = []
        for key in keys:
            val = str( params[key] )
            pairs.append( urllib.quote(key, safe='') + '=' + urllib.quote(val, safe='-_~') )
            qs = '&'.join(pairs)
            
        target = 'GET\n%s\n%s\n%s' % (aws_pass.AWS_URL, aws_pass.AWS_PATH, qs)
        sig = base64.b64encode(hmac.new(aws_pass.AWS_SECRET_KEY, target, hashlib.sha256).digest())
        param_str = "%s&Signature=%s" % (qs, urllib.quote(sig) )
        return aws_pass.AWS_PATH + "?" + param_str

    def parse(self, xml):
        result = dict()
        items  = []

        dom = parseString(xml)
        result['TotalResults'] = dom.getElementsByTagName('TotalResults')[0].firstChild.data
        result['TotalPages']   = dom.getElementsByTagName('TotalPages')[0].firstChild.data
        result['Items']        = items

        items_dom =  dom.getElementsByTagName('Item')
        for item_dom in items_dom:
            item = dict()
            item['DetailPageURL']   = item_dom.getElementsByTagName('DetailPageURL')[0].firstChild.data
            item['Title']           = item_dom.getElementsByTagName('Title')[0].firstChild.data
            item['PublicationDate'] = item_dom.getElementsByTagName('PublicationDate')[0].firstChild.data
            item['Publisher']       = item_dom.getElementsByTagName('Publisher')[0].firstChild.data

            authors = []
            for author_dom in item_dom.getElementsByTagName('Author'):
                authors.append(author_dom.firstChild.data)
            item['Author'] = authors

            img_dom = item_dom.getElementsByTagName('SmallImage')
            if len(img_dom) > 0:
                item['ImgURL']    = img_dom[0].getElementsByTagName('URL')[0].firstChild.data
                item['ImgWidth']  = img_dom[0].getElementsByTagName('Width')[0].firstChild.data
                item['ImgHeight'] = img_dom[0].getElementsByTagName('Height')[0].firstChild.data

            if len(authors) == 1:
                query = db.GqlQuery("SELECT * FROM Node WHERE id_str = :id_str", id_str=authors[0])
                if query.count() > 0:
                    data = query.fetch(1)[0]
                    item['NodeX'] = float(data.x)
                    item['NodeY'] = float(data.y)
            items.append(item)
        return result
        


# WSGI
application = webapp.WSGIApplication([
        ('/aws_search_books', SearchBooks),
        ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
